package gui.calendarview;

import gui.ActivityWindow;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Date;

import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import no.ntnu.fp.model.ActivityModel;
import no.ntnu.fp.model.Person;
import no.ntnu.fp.swingutil.CalendarTools;

public class DayViewPanel extends CalendarView implements ListSelectionListener {

	private static final long serialVersionUID = 1L;
	private DayListComponent dayList;
	
	public DayViewPanel(Date date, Person user) {
		super(date,user);
		ct = new CalendarTools();
		dayList = new DayListComponent(date,true,user);
		dayList.addListSelectionListener(this);
		String dayName = ct.getDayName(date);
		JLabel day = new JLabel(dayName.substring(0, 1).toUpperCase() + dayName.substring(1));
		
		JPanel dayPanel = new JPanel();
		GridBagLayout gbl = new GridBagLayout();
		gbl.columnWidths = new int[] { 980 };
		gbl.rowHeights = new int[] { 20,450 };
		dayPanel.setLayout(gbl);
		GridBagConstraints c = new GridBagConstraints();
		addComponentToLayout(dayPanel, day,c,0,0,1,1, GridBagConstraints.CENTER);
		addComponentToLayout(dayPanel, dayList,c,0,1,1,1, GridBagConstraints.BOTH);
		
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		add(new JLabel("Dagsvisning"));
		add(dayPanel);
	}
	
	private void addComponentToLayout(JPanel panel, JComponent component, GridBagConstraints c, int x, int y, int height, int width, int fill) {
		c.gridx = x;
		c.gridy = y;
		c.gridwidth = width;
		c.gridheight = height;
		c.fill = fill;
		panel.add(component, c);
	}
	
	public void setCurrentDateShowing(Date date) {
		currentDateShowing = date;
		dayList.setDay(date);
	}
	
	public void updateList() {
		dayList.updateList();
	}

	public void valueChanged(ListSelectionEvent e) {
		Object o = dayList.getSelectedValue();
		if ( o != null ) {
			ActivityModel model = ((ListElement)o).getModel();
			if ( model != null )
				if ( isAllowedToOpenWindow ) {
					new ActivityWindow(model);
					updateList();
					isAllowedToOpenWindow = false;
				} else {
					isAllowedToOpenWindow = true;
				}
		}		
	}

	public JList getList() {
		return dayList;
	}
	
}
